/*
 * Copyright © 2011 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.classes;

import java.util.Vector;
import javax.microedition.rms.*;

/**
 *
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class PhoneBookRMSManager {
	
	private static RecordStore rs = null;
	
	public static void openRecordStore() {
		try {
			rs = RecordStore.openRecordStore(PhoneBookConfig.record_store_name, true);
		} catch(Exception ex) {
			System.out.println("exception in opening record store \"" + PhoneBookConfig.record_store_name + "\"");
		}
	}
	
	public static void closeRecordStore() {
		if (rs != null) {
			try {
				rs.closeRecordStore();
			} catch(Exception ex) {
				
			}
		}	
	}
	
	public static Vector getAllContacts() {
		Vector vector = new Vector();
		try {
			openRecordStore();
			RecordEnumeration re = rs.enumerateRecords(null, null, false);
			while (re.hasNextElement()) {
				byte[] data = re.nextRecord();
				PhoneBookContact contact = PhoneBookContact.byteArray2Object(data);
				vector.addElement(contact);
                                System.out.println(contact.getCname());
			}
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			closeRecordStore();
		}
		return vector;
	}
	
	public static void addContact(PhoneBookContact contact) {
		try {
			openRecordStore();
			byte[] data = contact.object2ByteArray();
			rs.addRecord(data, 0, data.length);
		} catch(Exception ex) {
			
		} finally {
			closeRecordStore();
		}
	}

	public static void delContact(String content) {
		try {
			openRecordStore();
			int nextRecordID = rs.getNextRecordID();
			for (int i = 1; i < nextRecordID; i++) {
				byte[] data = rs.getRecord(i);
				PhoneBookContact contact = PhoneBookContact.byteArray2Object(data);
				if ((contact.getCname()+":"+contact.getPhone()).equals(content)) {
					rs.deleteRecord(i);
				}
			}
		} catch(Exception ex) {
			
		} finally {
			
		}
		closeRecordStore();
	}
}
